package com.myphoto.base.advice;

import com.myphoto.base.enumtype.MsgEnum;
import com.myphoto.base.util.R;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class Jsr303ExceptionAdvice {

    /**
    * @description 参数校验拦截
    * @author 方安伦
    * @date 2021/12/10 11:42
     **/
    @ExceptionHandler(value= {MethodArgumentNotValidException.class , BindException.class})
    public R handleVaildException(Exception e){
        BindingResult bindingResult = null;
        if (e instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException)e).getBindingResult();
        } else if (e instanceof BindException) {
            bindingResult = ((BindException)e).getBindingResult();
        }
        Map<String,String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError)->
                errorMap.put(fieldError.getField(),fieldError.getDefaultMessage())
        );
        return R.error(MsgEnum.PARAM_ERROR,errorMap);
    }
}
